package com.mantru.iotpot.Adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity.INPUT_METHOD_SERVICE
import com.mantru.iotpot.Adapter.Base.AppAdapter
import com.mantru.iotpot.Adapter.Base.AppHolder
import com.mantru.iotpot.Bean.DishesListBean
import com.mantru.iotpot.R
import com.mantru.iotpot.Util.MathUtil

class DishesListAdapter(var context: Context, layoutResId: Int, var data: MutableList<DishesListBean>): AppAdapter<DishesListBean>(context, layoutResId, data) {

    private var dishesListListener: DishesListListener? = null
    fun setDishesListListener(dishesListListener: DishesListListener?) {
        this.dishesListListener = dishesListListener
    }
    interface DishesListListener {
        fun onDelete(position: Int)
        fun setNum(position: Int, value: String)
        fun setWeight(position: Int, value: String)
    }

    override fun convert(holder: AppHolder?, position: Int, item: DishesListBean) {

        var weight: EditText? = null
        holder?.setOnClickListener(R.id.adapter_dishes_delete_button){//设置删除点击事件
                dishesListListener!!.onDelete(position)
            }
            ?.setOnClickListener(R.id.adapter_dishes_num){//设置分量弹窗弹出点击事件
                showPortionDialog(position, holder)
            }
            ?.setText(R.id.adapter_dishes_num_textview, item.num)//填入已有分量
            ?.setText(R.id.adapter_dishes_weight_editText, item.weight)//填入已有重量
            ?.setVisibility(R.id.adapter_dishes_delete_button, data.size != 1)//当列表长度为1,则无法删除


        weight = holder?.getView<EditText>(R.id.adapter_dishes_weight_editText)

        weight!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //这里要新增逻辑，如果输入了0开头，而非0的数据，要把开头的0去掉
                dishesListListener?.setWeight(holder!!.layoutPosition, MathUtil.trimLeadingZeros(s.toString()))
            }

            override fun afterTextChanged(s: Editable?) {}
        })

        //监听输入框回车按键
        weight.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_NEXT
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEND) {

                // 获取输入法管理器
                val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
                // 隐藏软键盘
                imm?.hideSoftInputFromWindow(v.windowToken, 0)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
    }

    @SuppressLint("SetTextI18n")
    //弹出份数弹窗
    private fun showPortionDialog(position: Int, holder: AppHolder?) {
        val builder: AlertDialog.Builder = AlertDialog.Builder(context)
        builder.setTitle("选择份数")


        // 生成 1-3 份的数组
        val portions = arrayOfNulls<String>(3)
        for (i in 0..2) {
            portions[i] = (i + 1).toString() + "份"
        }

        builder.setItems(portions) { _, which ->
            val selected: Int = which + 1 // 获取选中的份数
            holder?.setText(R.id.adapter_dishes_num_textview, selected.toString() + "份")
            dishesListListener?.setNum(position, selected.toString() + "份")
        }

        builder.show()
    }

    @SuppressLint("NotifyDataSetChanged")
    //刷新数据
    fun updateData(newData: List<DishesListBean>) {
        Log.e("--list", newData.size.toString())
        (context as? Activity)?.runOnUiThread {
            (mItems as? MutableList)?.apply {
                clear()
                addAll(newData)
            }
            notifyDataSetChanged()
        }
    }
}